﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CetWin.Phone.Entity;
using PF = Phone.Framework;
using CetWin.Phone.Services;
using Caliburn.Micro;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections;
using Phone.Framework;
using System.Linq;
using Phone.Framework.Threads;
using System.Collections.Generic;
using System.Threading;
using Phone.Framework.CaliburnExtensions.Results;
using Phone.Framework.CaliburnExtensions;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using Phone.Framework.Data;
using Phone.Framework.Media;
namespace CetWin.ViewModels
{
    public class WordDetailViewModel : Screen
    {

        #region NewCode

        private byte[] buffer;
        private MemoryStream stream;
        private Recording r;

        private SoundEffectInstance soundInstance;
        private DateTime lastPlayFrame;
        private IApplicationBarIconButton btnSpeak;
        private IApplicationBarIconButton btnVoice;

        private AudioState currentState = AudioState.Stopped;

        public AudioState CurrentState
        {
            get { return this.currentState; }
            set { this.currentState = value; }
        }
        DispatcherTimer timer = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(3)
        };

        protected override void OnDeactivate(bool close)
        {
            CompositionTarget.Rendering -= CompositionTarget_Rendering;
            Microphone.Default.BufferReady -= Microphone_BufferReady;
            base.OnDeactivate(close);
        }

        private void InitState()
        {
            CompositionTarget.Rendering += CompositionTarget_Rendering;

            FrameworkDispatcher.Update();

        //    Microphone.Default.BufferDuration = TimeSpan.FromSeconds(.1);
            Microphone.Default.BufferReady += Microphone_BufferReady;


            int size = Microphone.Default.GetSampleSizeInBytes(Microphone.Default.BufferDuration);
            this.buffer = new byte[size];

            this.stream = new MemoryStream();

            Microphone.Default.Start();

            timer.Tick += new EventHandler(timer_Tick);
        }

        void timer_Tick(object sender, EventArgs e)
        {

            CurrentState = AudioState.Stopped;
            MessageBox.Show("Record finished.");

            r = new Recording
            {
                Filename = SelectedWord.Name,
                TimeStamp = DateTimeOffset.Now
            };

            r.SaveContent(this.stream);

            this.stream.Position = 0;

            timer.Stop();
            if (btnSpeak != null)
            {
                btnSpeak.IsEnabled = true;
            }
            if (btnVoice != null)
            {
                btnVoice.IsEnabled = true;
            }
            PlayRecord();
        }


        void Microphone_BufferReady(object sender, EventArgs e)
        {
            int size = Microphone.Default.GetData(this.buffer);
            if (size == 0)
                return;

            if (CurrentState == AudioState.Recording)
            {
                this.stream.Write(this.buffer, 0, size);
                TimeSpan recordingLength = Microphone.Default.GetSampleDuration((int)this.stream.Position);
            }
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            FrameworkDispatcher.Update();
        }

        void Play()
        {
            this.lastPlayFrame = DateTime.Now;

            this.soundInstance.Play();

        }
        #endregion


        private readonly HistoryService _historyService;
        private readonly SearchRecordService _searchRecordService;
        private readonly WordService _wordService;
        private readonly INavigationService _navigationService;
        private readonly CetWinSetting _setting;

        public WordDetailViewModel(INavigationService navigationService)
        {


            _historyService = IoC.Get<HistoryService>();
            _searchRecordService = IoC.Get<SearchRecordService>();
            _wordService = IoC.Get<WordService>();
            _navigationService = IoC.Get<INavigationService>();
            _setting = IoC.Get<CetWinSetting>();

            SelectedWord = PhoneStateManager.GetAppState<Word>(GlobalConstant.SelectedWordField);

            ThreadManager.Instance.AddTask(() =>
            {

                if (UIThread.Dispatcher.CheckAccess())
                {
                    SelectedWord.WordExtesion = _wordService.GetWordExtesion(SelectedWord.Name);
                    _historyService.UpdateSearchRecords(SelectedWord.Name);
                }
                else
                {
                    var we = _wordService.GetWordExtesion(SelectedWord.Name);
                    _historyService.UpdateSearchRecords(SelectedWord.Name);
                    UIThread.Invoke(() =>
                    {
                        SelectedWord.WordExtesion = we;
                    });
                }
            });

            InitState();

        }

        protected override void OnInitialize()
        {
            if (_setting.AutoNetworkSearch && SelectedWord.Audio == null)
            {
               
                _wordService.AsyncUpdateNetWord(SelectedWord, () =>
                {
                    NotifyOfPropertyChange(() => CanPlayVoice);
                    NotifyOfPropertyChange(() => CanAddToHistory);
                    if (_setting.AutoSpellWord)
                    {
                        IoC.Get<IMediaPlayService>().Play(SelectedWord.Audio, null);
                    }
                });
            }

            if (_setting.AutoSpellWord && SelectedWord.Audio != null)
            {
                IoC.Get<IMediaPlayService>().Play(SelectedWord.Audio, null);
            }
            base.OnInitialize();
        }

        protected override void OnActivate()
        {
            base.OnActivate();
            ThreadManager.Instance.AddTask(() =>
            {
                CanSwitchHistoryIcon = _historyService.UpdateTime(SearchText);
            });
        }

        #region Method

        #region NewCode


        public void SpeakRecord()
        {
            btnSpeak = (_navigationService.CurrentContent as PhoneApplicationPage).ApplicationBar.Buttons[0] as IApplicationBarIconButton;
            btnVoice = (_navigationService.CurrentContent as PhoneApplicationPage).ApplicationBar.Buttons[1] as IApplicationBarIconButton;
            if (btnSpeak != null)
                btnSpeak.IsEnabled = false;
            if (btnVoice != null)
                btnVoice.IsEnabled = false;
            //using (IsolatedStorageFile userStore =
            //  IsolatedStorageFile.GetUserStoreForApplication())
            //{
            //    if (userStore.FileExists(SelectedWord.Name))
            //    {
            //        PlayRecord();
            //    }
            //    else
            //    {
            CurrentState = AudioState.Recording;

            timer.Start();
            //    }
            //}
        }

        public void PlayRecord()
        {
            if (r != null)
            {
                this.soundInstance = r.GetContent().CreateInstance();
                Play();
            }
        }
        #endregion

        public void GoHome()
        {
            _navigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.RelativeOrAbsolute));
            //   _navigationService.UriFor<MainPageViewModel>().Navigate();
        }

        public bool CanPlayVoice
        {
            get
            {
                return SelectedWord.Audio != null && _setting.AutoNetworkSearch;
            }
        }

        public IEnumerable<IResult> PlayVoice()
        {
            return ResultHelper.AppButtonAction((IActionResult result) =>
            {
                btnSpeak = (_navigationService.CurrentContent as PhoneApplicationPage).ApplicationBar.Buttons[0] as IApplicationBarIconButton;
               
                if (btnSpeak != null)
                    btnSpeak.IsEnabled = false;

                IoC.Get<IMediaPlayService>().Play(SelectedWord.Audio, () =>
                {
                    if (btnSpeak != null)
                        btnSpeak.IsEnabled = true;
                    result.Set();
                });
            });
        }

        public bool CanAddToHistory
        {
            get
            {
                if (_setting.AutoNetworkSearch)
                    return SelectedWord.Audio != null;
                return true;
            }
        }

        public void AddToHistory()
        {
            ThreadManager.Instance.AddTask(() =>
            {
                _historyService.SaveHistory(SelectedWord.Name, CanSwitchHistoryIcon);
            });

            CanSwitchHistoryIcon = !CanSwitchHistoryIcon;
            IoC.Get<IEventAggregator>().Publish(new HandleMessage(Messages.UpdateHistroy));
        }

        #endregion

        #region Property


        private bool _canSwitchHistoryIcon;
        public bool CanSwitchHistoryIcon
        {
            get { return _canSwitchHistoryIcon; }
            set
            {
                _canSwitchHistoryIcon = value;
                NotifyOfPropertyChange(() => CanSwitchHistoryIcon);
            }
        }

        private string _searchText;
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                NotifyOfPropertyChange(() => SearchText);
            }
        }

        private WordExtesion _extesion;

        public WordExtesion Extesion
        {
            get { return _extesion; }
            set
            {
                _extesion = value;
                NotifyOfPropertyChange(() => Extesion);
            }
        }

        public void UpateExtesion()
        {
            //if (Extesion.Name == null)
            //{
            //    Extesion.Name = SearchText;
            //    dc.WordExtesions.InsertOnSubmit(Extesion);
            //}
            //dc.SubmitChanges();
        }

        private Word _selectedWord;

        public Word SelectedWord
        {
            get { return _selectedWord; }
            set
            {
                _selectedWord = value;
                NotifyOfPropertyChange(() => SelectedWord);
            }
        }

        private int _selectedPivotIndex;

        public int SelectedPivotIndex
        {
            get { return _selectedPivotIndex; }
            set
            {
                _selectedPivotIndex = value;
                NotifyOfPropertyChange(() => SelectedPivotIndex);
            }
        }


        private Uri _browserURL;
        public Uri BrowserURL
        {
            get { return _browserURL; }
            set
            {
                _browserURL = value;
                NotifyOfPropertyChange(() => BrowserURL);
            }
        }

        public void ChangePivot(int index)
        {
            UIThread.Invoke(() =>
            {
                if (SelectedPivotIndex == 1 && BrowserURL == null)
                {
                    BrowserURL = new Uri(string.Format(GetUrlFromSetting(), SelectedWord.Name));
                }
                else
                if (SelectedPivotIndex == 2 && ImageResult == null)
                {
                    SearchImage();

                }
            });
        }

        private IEnumerable _imageResult;
        public IEnumerable ImageResult
        {
            get { return _imageResult; }
            set
            {
                _imageResult = value;
                NotifyOfPropertyChange(() => ImageResult);
            }
        }

        private void SearchImage()
        {
            BingImageSearch.Search(SelectedWord.Name, 20, new Action<ImageSearchResponse>
                ((ImageSearchResponse obj) =>
                {
                    UIThread.Invoke(() =>
                    {
                        if (obj.SearchResponse.Image.Total > 0)
                        {
                            ImageResult = obj.SearchResponse.Image.Results;
                        }
                        else
                        {
                            ImageResult = null;
                        }
                    });
                }));
        }

        private string GetUrlFromSetting()
        {
            var engine = _setting.SearchEngine;
            switch (engine)
            {
                case "youdao":
                    return "http://dict.youdao.com/m/search?q={0}";
                case "iciba":
                    return "http://wap.iciba.com/dict/w/?search_word={0}";
            }
            return string.Empty;
        }

        #endregion
    }




}
